import TauActionPanel from '@/components/TauActionPanel';
import TauPage from '@/components/TauPage';
import TauTable from '@/components/TauTable';
import { useStore } from '@/hooks';
import { Balloon, Box, Button, Dialog, Drawer, List, Message, Tab, Upload } from '@alifd/next';
import { t } from '@lingui/macro';
import { toJS } from 'mobx';
import { observer } from 'mobx-react-lite';
import React, { useEffect, useRef, useState } from 'react';
import RuleForm from './components/RuleForm';
import styles from './index.module.scss';
import { column, showAttr } from './stores/definitions';

function Rule() {
  const [uploading, setUploading] = useState(false);
  const [modal, setModal] = useState([]);
  const [tags, setTags] = useState([]);
  const { ruleStore: store } = useStore();
  const objRef = useRef(); // 当前选中的对象

  useEffect(() => {
    (async () => {
      const res = await store.api.tags();
      setTags(['0', ...res.sort((a, b) => a.localeCompare(b))]);
    }
    )();
  }, []);

  // 获取列表数据
  const handleOnSearch = (params) => {
    const { upDate, ...searchArgs } = params.values;
    const [from, to] = upDate || [];
    store.search = {
      from,
      to,
      ...searchArgs,
    };
  };

  async function checkDuplicate(id) {
    return new Promise((resolve) => {
      store.api.checkExists(id).then((res) => {
        if (res === true) {
          Dialog.confirm({
            title: t`规则已存在`,
            content: <Box spacing={6}><span>{t`继续上传会覆盖现有规则。`}</span><span>{t`是否上传？`}</span></Box>,
            onOk: () => resolve(true),
            onCancel: () => resolve(false),
          });
        } else {
          resolve(true);
        }
      });
    });
  }

  const handleRequest = ({ file, onSuccess, onError }) => {
    const reader = new FileReader();
    reader.onloadend = async () => {
      setUploading(true);
      try {
        // eslint-disable-next-line @iceworks/best-practices/recommend-polyfill
        const xml = new TextDecoder().decode(reader.result);
        const match = xml.match(/<dmn:definitions .*name="([^"]+)" .*namespace="([^"]+)".*>/);
        const ruleId = match[1];
        if (!ruleId) {
          Message.error(t`规则文件格式错误.`);
          return;
        }
        const rtn = await checkDuplicate(ruleId);
        if (!rtn) return;
        await store.api.uploadRule(Buffer.from(reader.result));
        onSuccess?.(file);
        Message.success(t`规则上传成功`);
      } catch (e) {
        onError?.(e);
        Message.error(t`规则上传失败.`);
      } finally {
        setUploading(false);
      }
    };
    reader.readAsArrayBuffer(file);
  };

  function handleDownload(rule) {
    store.api.downloadRule(rule.id).then((data) => Util.saveBlob(data, { filename: `${rule.id}_${rule.name}.dmn`, mimeType: 'text/xml' }));
  }

  // 点击打开查看
  const handleOpenView = (current) => {
    // objRef.current = current;
    // setModal(['view']);
  };

  // Modal窗口关闭回调
  const handleCancel = () => {
    setModal([]);
  };

  const handleDelete = (rule) => {
    Dialog.confirm({
      title: t`删除规则【${rule.name}(${rule.id})】`,
      content: <Box spacing={6}><span>{t`删除已被使用规则可能导致相关功能异常，请确认该规则未被使用再行删除。`}</span><span>{t`是否确认删除？`}</span></Box>,
      onOk: () => store.remove(rule),
    });
  };

  function attrs(v) {
    if (_.isEmpty(v)) return t`无`;
    const flatten = Util.flattenObject(v, '', (o) => (typeof o === 'object' && o.lowBoundary ? o : undefined));
    return (
      <Balloon v2 trigger={<Button type="primary" text>{t`查看`}</Button>} triggerType="hover" title={t`规则属性`} popupClassName="pupup-rule-props" align="r">
        <List
          size="small"
          dataSource={Object.keys(flatten)}
          renderItem={(name, i) => (
            <List.Item
              key={i}
              extra={showAttr(flatten[name])}
              title={`${name}: `}
            />
          )}
        />
      </Balloon>

    );
  }

  return (
    <TauPage className={`page-container ${styles.Rule}`}>
      <TauActionPanel
        onSearch={handleOnSearch}
        actions={[
          {
            name: 'btn-placeRule',
            component: (
              <Upload
                accept=".dmn"
                onSuccess={() => store.query()}
                request={handleRequest}
              >
                <Button type="primary" loading={uploading}>{t`上传规则`}</Button>
              </Upload>
            ),
          },
        ]}
        searchItems={[
          {
            name: 'upDate',
            type: 'date-range',
            props: {
              placeholder: [t`起始更新时间`, t`结束更新时间`],
            },
          },
        ]}
        keywordSearch={{
          placeholder: t`请输入关键字搜搜`,
        }}
        className="action-panel"
      />
      <div className="content">
        <Tab
          activeKey={`${store.tag}`}
          onChange={(v) => { store.tag = v; }}
          excessMode="dropdown"
          size="small"
        >
          {tags.map((tag) => <Tab.Item key={tag} title={tag === '0' ? t`全部` : tag} />)}
        </Tab>

        <TauTable
          primaryKey="id"
          tableLayout="fixed"
          currentPage={store.pg.page}
          pageSize={store.pg.size}
          total={store.total}
          sort={store.tableSort}
          onFetch={(pg) => { store.pg = pg; }}
          loading={store.loading}
          dataSource={toJS(store.data)}
          columns={[
            { title: t`序号`, dataIndex: 'idx', width: 44, cell: (v, i) => store.idx(i) },
            column('id', { width: 208, sortable: true, cell: (v, _, rule) => <Button type="primary" text onClick={() => handleOpenView(rule)}>{v}</Button> }),
            column('name', { sortable: true }),
            column('tags', { width: 100, sortable: true }),
            column('attributes', { width: 80, cell: (v) => attrs(v) }),
            column('upDate', { width: 124, sortable: true }),
            column('upBy', { width: 120 }),
            {
              title: t`操作`,
              dataIndex: 'id',
              width: 100,
              cell: (_, __, rule) => (
                <>
                  <Button text type="primary" onClick={() => handleDownload(rule)} >{t`下载`}</Button>
                  <span style={{ color: 'var(--btn-text-primary-color, #5584FF)' }}> | </span>
                  <Button text type="primary" onClick={() => handleDelete(rule)} >{t`删除`}</Button>

                </>),
            },
          ].filter((c) => store.tag === '0' || c.dataIndex !== 'tags')}
        />
      </div>
      <Drawer
        visible={modal[0] === 'add' || modal[0] === 'edit' || modal[0] === 'view'}
        title={modal[0] === 'add' ? t`添加规则` : t`修改规则【${objRef.current?.name}】`}
        style={{ maxWidth: '90%' }}
        closeMode={['esc', 'mask', 'close']}
        onClose={() => setModal([...modal, `toClose$${Date.now()}`])}
        width="90%"
      >
        <RuleForm
          ruleId={objRef.current?.id}
          modal={modal}
          onCancel={handleCancel}
        // onSubmit={modal[0] === 'add' ? handleCreate : handleUpdate}
        />
      </Drawer>

    </TauPage>
  );

}

export default observer(Rule);
